<template>
  <Dialog v-model="dialogVisible" title="选择商品" width="75%">
    <div class="h-600px">
      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="mb-4">
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-tree-select
            v-model="queryParams.categoryId"
            :data="categoryOptions"
            :props="defaultProps"
            check-strictly
            node-key="id"
            placeholder="请选择商品分类"
            show-checkbox
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <Icon icon="ep:search" class="mr-5px" />
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px" />
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 商品列表 -->
      <el-table
        v-loading="loading"
        :data="list"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        class="h-350px"
        :row-class-name="getRowClassName"
        highlight-current-row
        @current-change="handleTableCurrentChange"
      >
        <el-table-column type="selection" width="55" v-if="multiple" />
        <el-table-column label="商品图" width="100">
          <template #default="{ row }">
            <el-image
              v-if="row.picUrl"
              :src="row.picUrl"
              class="h-60px w-60px"
              @click="imagePreview(row.picUrl)"
            />
          </template>
        </el-table-column>
        <el-table-column label="商品名称" prop="name" show-overflow-tooltip />
        <el-table-column label="商品价格" prop="price" width="120">
          <template #default="{ row }">
            ￥{{ fenToYuan(row.price) }}
          </template>
        </el-table-column>
        <el-table-column label="销量" prop="salesCount" width="100" />
        <el-table-column label="库存" prop="stock" width="100" />
        <el-table-column label="状态" prop="status" width="100">
          <template #default="{ row }">
            <dict-tag :type="DICT_TYPE.PRODUCT_SPU_STATUS" :value="row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" v-if="!multiple">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleSelect(row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="flex justify-center items-center mt-4 gap-4">
        <span class="text-sm text-gray-600">共 {{ total }} 条</span>
        <span class="text-sm text-gray-600">6条/页</span>
        <el-pagination
          v-model:current-page="queryParams.pageNo"
          :total="total"
          :page-size="queryParams.pageSize"
          layout="prev, pager, next"
          @current-change="handlePageChange"
          small
        />
        <div class="flex items-center gap-2">
          <span class="text-sm text-gray-600">前往</span>
          <el-input
            v-model="jumpPage"
            class="!w-50px"
            size="small"
            @keyup.enter="handleJumpToPage"
          />
          <span class="text-sm text-gray-600">页</span>
        </div>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <template #footer>
      <el-button type="primary" @click="handleConfirm" v-if="multiple">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { DICT_TYPE } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import * as ProductSpuApi from '@/api/mall/product/spu'
import * as ProductCategoryApi from '@/api/mall/product/category'
import { createImageViewer } from '@/components/ImageViewer'
import { fenToYuan } from '@/utils'

/** 商品选择对话框 */
defineOptions({ name: 'ProductSelectDialog' })

const props = defineProps<{
  multiple?: boolean // 是否多选
}>()

const emit = defineEmits<{
  change: [product: ProductSpuApi.Spu | ProductSpuApi.Spu[]]
}>()

const dialogVisible = ref(false)
const loading = ref(false)
const total = ref(0)
const list = ref<ProductSpuApi.Spu[]>([])
const selectedProducts = ref<ProductSpuApi.Spu[]>([])
const categoryOptions = ref<any[]>([])
const selectedProduct = ref<ProductSpuApi.Spu | null>(null)
const jumpPage = ref('')

const queryParams = ref({
  pageNo: 1,
  pageSize: 6,
  name: '',
  categoryId: undefined,
  tabType: 0 // 默认获取上架的商品
})

const queryFormRef = ref()

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProductSpuApi.getSpuPage(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProductSpuApi.Spu[]) => {
  selectedProducts.value = selection
}

/** 行点击事件 */
const handleRowClick = (row: ProductSpuApi.Spu) => {
  if (!props.multiple) {
    selectedProduct.value = row
    handleSelect(row)
  }
}

/** 选择商品 */
const handleSelect = (row: ProductSpuApi.Spu) => {
  if (props.multiple) {
    // 多选模式：添加到选中列表
    const index = selectedProducts.value.findIndex(item => item.id === row.id)
    if (index === -1) {
      selectedProducts.value.push(row)
    }
  } else {
    // 单选模式：直接选择并关闭对话框
    selectedProduct.value = row
    emit('change', row)
    dialogVisible.value = false
  }
}

/** 当前行改变事件 */
const handleTableCurrentChange = (currentRow: ProductSpuApi.Spu | null) => {
  if (!props.multiple && currentRow) {
    selectedProduct.value = currentRow
  }
}

/** 获取行样式 */
const getRowClassName = ({ row }: { row: ProductSpuApi.Spu }) => {
  if (!props.multiple && selectedProduct.value?.id === row.id) {
    return 'selected-row'
  }
  return ''
}

/** 确认选择 */
const handleConfirm = () => {
  if (props.multiple) {
    emit('change', selectedProducts.value)
  }
  dialogVisible.value = false
}

/** 图片预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    zIndex: 99999999,
    urlList: [imgUrl]
  })
}

/** 打开对话框 */
const open = () => {
  dialogVisible.value = true
  selectedProducts.value = []
  selectedProduct.value = null
  getList()
  // 加载商品分类
  if (categoryOptions.value.length === 0) {
    loadCategories()
  }
}

/** 加载商品分类 */
const loadCategories = async () => {
  try {
    const data = await ProductCategoryApi.getCategoryList({})
    categoryOptions.value = handleTree(data, 'id', 'parentId')
  } catch (error) {
    console.error('Failed to load categories:', error)
  }
}

/** 当前页改变 */
const handlePageChange = (newPage: number) => {
  queryParams.value.pageNo = newPage
  getList()
}

/** 跳转到指定页 */
const handleJumpToPage = () => {
  const page = parseInt(jumpPage.value)
  if (page && page > 0 && page <= Math.ceil(total.value / queryParams.value.pageSize)) {
    queryParams.value.pageNo = page
    getList()
    jumpPage.value = ''
  }
}

defineExpose({ open })
</script>

<style scoped lang="scss">
:deep(.el-dialog__body) {
  padding-bottom: 0;
}

:deep(.selected-row) {
  background-color: var(--el-color-primary-light-9) !important;
  
  &:hover {
    background-color: var(--el-color-primary-light-8) !important;
  }
}

:deep(.el-table__body tr.current-row) {
  background-color: var(--el-color-primary-light-9) !important;
}
</style> 